package com.hengtiansoft.lfy.net;

import android.content.Context;
import android.util.Log;

import com.duowan.mobile.netroid.DefaultRetryPolicy;
import com.duowan.mobile.netroid.Listener;
import com.duowan.mobile.netroid.NetroidError;
import com.duowan.mobile.netroid.Request;
import com.duowan.mobile.netroid.RequestQueue;
import com.duowan.mobile.netroid.request.JsonObjectRequest;
import com.duowan.mobile.netroid.request.StringRequest;
import com.google.gson.Gson;
import com.hengtiansoft.lfy.LFYApplication;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.entity.EvaluatorMessageEntity;
import com.hengtiansoft.lfy.entity.EvaluatorModeEntity;
import com.hengtiansoft.lfy.entity.EvaluatorRankings;
import com.hengtiansoft.lfy.entity.ServiceResult;
import com.hengtiansoft.lfy.utils.EvaParser;
import com.hengtiansoft.lfy.utils.Utils;
import com.hengtiansoft.lfy.widget.CProgressDialog;

import org.json.JSONObject;

import java.util.List;
import java.util.Map;

/**
 * Created by daiye on 2016/10/25 0025.
 */

public class NetUtils {
    private static RequestQueue mQueue = Netroid.newRequestQueue(LFYApplication.getInstance(), null);

    // POST
    public static void post(final Context context, String postBaseUrl, final Map<String, String> map, final NetCallBack<ServiceResult> callBack, final Class<?> rspCls) {
        if (!Utils.isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed(context.getResources().getString(R.string.network_not_connected));
            return;
        }
        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.NetProcessDialog);
        progressDialog.setMessage("Fetching data!");
        progressDialog.setCancelable(true);
        try {
            if (!progressDialog.isShowing()) {
                progressDialog.show();
            }
        } catch (Exception e) {
        }

        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(postBaseUrl, params, new com.duowan.mobile.netroid.Listener<JSONObject>() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                progressDialog.dismiss();
//				int retcode = getRetCode(jsonObject);
//				if (retcode != 0) {
//					if (callBack != null)
//						callBack.failed(context.getResources().getString(R.string.networkerror));
//					return;
//				}
                ServiceResult rsp = null;
                try {
                    Gson gson = new Gson();
                    rsp = (ServiceResult) gson.fromJson(jsonObject.toString(), rspCls);
                } catch (Exception e) {
                    Log.e("NetUtils", "post RspMsgError");
                    e.printStackTrace();
                }
                if (callBack != null)
                    if (rsp != null) {
                        callBack.success(rsp);
                    } else {
                        callBack.failed(context.getResources().getString(R.string.network_parsing_error));
                    }
            }

            @Override
            public void onError(NetroidError error) {
                progressDialog.dismiss();
                if (callBack != null)
                    callBack.failed(context.getResources().getString(R.string.network_unknown_error));
            }
        });

        request.setRetryPolicy(new DefaultRetryPolicy(6 * 1000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(request);
    }
    public static void get(final Context context, String method, final String msg, final NetCallBack<ServiceResult> callBack, final Class<?> rspCls) {
        if (!Utils.isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed(context.getResources().getString(R.string.network_unknown_error));
            return;
        }

        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.CustomDialog);
        if (msg != null) {
            progressDialog.setMessage(msg);
            progressDialog.setCancelable(true);
            try {
                if (!progressDialog.isShowing()) {
                    progressDialog.show();
                }
            } catch (Exception e) {

            }
        }

        String url =  method;

        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Listener<String>() {

                    @Override
                    public void onSuccess(String response) {
                        progressDialog.dismiss();
                        ServiceResult rsp = null;

                        try {
                            Gson gson = new Gson();
                            rsp = (ServiceResult) gson.fromJson(response.toString(), rspCls);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (callBack != null)
                            if (rsp != null) {
                                callBack.success(rsp);
                            } else {
                                callBack.failed(context.getResources().getString(R.string.network_parsing_error));
                            }
                    }

                    @Override
                    public void onError(NetroidError error) {
                        progressDialog.dismiss();
                        if (callBack != null)
                            callBack.failed(context.getResources().getString(R.string.network_unknown_error));
                    }
                });
        request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, 20, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(request);
    }

    public static void post(final Context context, final String url, final Map<String, Object> map, final String msg, final NetCallBack<ServiceResult> callBack, final Class<?> rspCls) {
        Log.i("supeng",map.toString()+","+url);
        if (!Utils.isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed(context.getResources().getString(R.string.network_not_connected));
            return;
        }
        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.NetProcessDialog);
        if (msg != null) {
            progressDialog.setMessage(msg);
            progressDialog.setCancelable(true);
            try {
                if (!progressDialog.isShowing()) {
                    progressDialog.show();
                }
            } catch (Exception e) {

            }
        }
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest( url, params, new com.duowan.mobile.netroid.Listener<JSONObject>() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                Log.i("supeng",jsonObject.toString());
                progressDialog.dismiss();
                ServiceResult rsp = null;
                try {
                    Gson gson = new Gson();
                    rsp = (ServiceResult) gson.fromJson(jsonObject.toString(), rspCls);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (callBack != null)
                    if (rsp != null) {
                        callBack.success(rsp);
                    } else {
                        callBack.failed(context.getResources().getString(R.string.network_parsing_error));
                    }
            }

            @Override
            public void onError(NetroidError error) {
                if (callBack != null) {
                    callBack.failed(context.getResources().getString(R.string.network_unknown_error));
                }
                progressDialog.dismiss();
            }
        });

        request.setRetryPolicy(new DefaultRetryPolicy(6 * 1000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(request);
    }

    // 获取评测试题
    public static void jsonPostEvMode(final Context context, final NetUtils.NetCallBack<List<EvaluatorModeEntity>> callBack, String post_url, final Map<String, Object> mapRequest, String msg) {
        if (!Utils.isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed(context.getResources().getString(R.string.network_not_connected));
            return;
        }

        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.CustomDialog);
        progressDialog.setCancelable(true);
        if( msg != null ){
            progressDialog.setMessage(msg);
            try {
                if (!progressDialog.isShowing()) {
                    progressDialog.show();
                }
            } catch (Exception e) {
            }
        }

        JSONObject params = new JSONObject(mapRequest);
        JsonObjectRequest request = new JsonObjectRequest(post_url, params, new Listener<JSONObject>() {
            @Override
            public void onSuccess(JSONObject jsonObject) {

                progressDialog.dismiss();
//                Log.d("tag","jsonObject = "+jsonObject.toString());
                List<EvaluatorModeEntity> list = EvaParser.getInstance().parseEvaluatorMode(jsonObject);
                if (callBack != null) {
                    if (list != null) {
                        callBack.success(list);
                    } else {
                        callBack.failed(context.getResources().getString(R.string.network_parsing_error));
                    }
                }
            }

            @Override
            public void onError(NetroidError error) {
                if (callBack != null) {
                    callBack.failed(context.getResources().getString(R.string.network_unknown_error));
                }
                progressDialog.dismiss();
            }
        });

        request.setRetryPolicy(new DefaultRetryPolicy(4 * 1000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(request);
    }

    // 获取平测试题具体内容
    public static void jsonPostEv(final Context context, final NetUtils.NetCallBack<List<EvaluatorMessageEntity>> callBack, String post_url, final Map<String, Object> mapRequest, String msg) {
        if (!Utils.isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed(context.getResources().getString(R.string.network_not_connected));
            return;
        }

        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.CustomDialog);
        progressDialog.setCancelable(true);
        if( msg != null ){
            progressDialog.setMessage(msg);
            try {
                if (!progressDialog.isShowing()) {
                    progressDialog.show();
                }
            } catch (Exception e) {
            }
        }

        JSONObject params = new JSONObject(mapRequest);
        JsonObjectRequest request = new JsonObjectRequest(post_url, params, new Listener<JSONObject>() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                progressDialog.dismiss();
//                Log.d("tag","EvaluatorMessageEntity jsonObject = "+jsonObject.toString());
                List<EvaluatorMessageEntity> list = EvaParser.getInstance().parseEvaluator(jsonObject);
                if (callBack != null) {
                    if (list != null) {
                        callBack.success(list);
                    } else {
                        callBack.failed(context.getResources().getString(R.string.network_parsing_error));
                    }
                }
            }

            @Override
            public void onError(NetroidError error) {
                if (callBack != null) {
                    callBack.failed(context.getResources().getString(R.string.network_unknown_error));
                }
                progressDialog.dismiss();
            }
        });

        request.setRetryPolicy(new DefaultRetryPolicy(4 * 1000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(request);
    }

    // 上传已完成练习，获取总成绩
    public static void jsonPostExercise(final Context context, final NetUtils.NetCallBack<EvaluatorRankings> callBack, String post_url, final Map<String, Object> mapRequest, String msg) {
        if (!Utils.isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed(context.getResources().getString(R.string.network_not_connected));
            return;
        }

        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.CustomDialog);
        progressDialog.setCancelable(true);
        if( msg != null ){
            progressDialog.setMessage(msg);
            try {
                if (!progressDialog.isShowing()) {
                    progressDialog.show();
                }
            } catch (Exception e) {
            }
        }

        JSONObject params = new JSONObject(mapRequest);
        JsonObjectRequest request = new JsonObjectRequest(post_url, params, new Listener<JSONObject>() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                progressDialog.dismiss();
                Log.d("tag","jsonObject = "+jsonObject.toString());

                EvaluatorRankings rankings = EvaParser.getInstance().parseEvaluatorRankings(jsonObject);
                if (callBack != null) {
                    if (rankings != null) {
                        callBack.success(rankings);
                    } else {
                        callBack.failed(context.getResources().getString(R.string.network_parsing_error));
                    }
                }
            }

            @Override
            public void onError(NetroidError error) {
                if (callBack != null) {
                    callBack.failed(context.getResources().getString(R.string.network_unknown_error));
                }
                progressDialog.dismiss();
            }


        });

        request.setRetryPolicy(new DefaultRetryPolicy(4 * 1000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(request);
    }

    // 上传已完成练习，获取总成绩
    public static void jsonPostExerciseHistory(final Context context, final NetUtils.NetCallBack<List<EvaluatorModeEntity>> callBack, String post_url, final Map<String, Object> mapRequest, String msg) {
        if (!Utils.isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed(context.getResources().getString(R.string.network_not_connected));
            return;
        }

        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.CustomDialog);
        progressDialog.setCancelable(true);
        if( msg != null ){
            progressDialog.setMessage(msg);
            try {
                if (!progressDialog.isShowing()) {
                    progressDialog.show();
                }
            } catch (Exception e) {
            }
        }

        JSONObject params = new JSONObject(mapRequest);
        JsonObjectRequest request = new JsonObjectRequest(post_url, params, new Listener<JSONObject>() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                progressDialog.dismiss();
                Log.d("tag","jsonObject = "+jsonObject.toString());
                List<EvaluatorModeEntity> list = EvaParser.getInstance().parseExerciseHistory(jsonObject);

                if (callBack != null) {
                    if (list != null) {
                        callBack.success(list);
                    } else {
                        callBack.failed(context.getResources().getString(R.string.network_parsing_error));
                    }
                }
            }

            @Override
            public void onError(NetroidError error) {
                if (callBack != null) {
                    callBack.failed(context.getResources().getString(R.string.network_unknown_error));
                }
                progressDialog.dismiss();
            }


        });

        request.setRetryPolicy(new DefaultRetryPolicy(4 * 1000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(request);
    }
    // 获取已完成的内容
    public static void jsonPostExerciseitem(final Context context, final NetUtils.NetCallBack<String> callBack, String post_url, final Map<String, Object> mapRequest, String msg) {
        if (!Utils.isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed(context.getResources().getString(R.string.network_not_connected));
            return;
        }

        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.CustomDialog);
        progressDialog.setCancelable(true);
        if( msg != null ){
            progressDialog.setMessage(msg);
            try {
                if (!progressDialog.isShowing()) {
                    progressDialog.show();
                }
            } catch (Exception e) {
            }
        }

        JSONObject params = new JSONObject(mapRequest);
        JsonObjectRequest request = new JsonObjectRequest(post_url, params, new Listener<JSONObject>() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                progressDialog.dismiss();
                if (callBack != null) {
                    if (jsonObject != null) {
                        callBack.success(jsonObject.toString());
                    } else {
                        callBack.failed(context.getResources().getString(R.string.network_parsing_error));
                    }
                }
            }

            @Override
            public void onError(NetroidError error) {
                if (callBack != null) {
                    callBack.failed(context.getResources().getString(R.string.network_unknown_error));
                }
                progressDialog.dismiss();
            }


        });

        request.setRetryPolicy(new DefaultRetryPolicy(4 * 1000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(request);
    }

    public static int getRetCode(JSONObject jsonObject) {
        try {
            return jsonObject.optInt("retcode");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }

    public interface NetCallBack<T> {
        public void success(T rspData);
        public void failed(String msg);
    }
}
